package org.dromara.commission.listener;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.dromara.commission.domain.vo.LzshAgentInfoRelationVo;
import org.dromara.commission.domain.vo.LzshHandworkCommissionImportVo;
import org.dromara.commission.domain.vo.LzshHandworkCommissionVo;
import org.dromara.commission.listener.redisPlus.RedisPlusImportListener;
import org.dromara.commission.service.ILzshHandworkCommissionService;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.satoken.utils.LoginHelper;

import java.util.List;

/**
 * 系统用户自定义导入
 *
 * @author Lion Li
 */
@Slf4j
@Data
public class LzshHandworkCommissionImportListener extends RedisPlusImportListener<LzshHandworkCommissionImportVo> {
    List<LzshAgentInfoRelationVo> infoList = null;
    List<LzshHandworkCommissionVo> hwcList;
    private final ILzshHandworkCommissionService lzshHandworkCommissionService;
    private boolean access = false;

    public LzshHandworkCommissionImportListener() {
        this.lzshHandworkCommissionService = SpringUtils.getBean(ILzshHandworkCommissionService.class);;
    }
    @Override
    public String key(LzshHandworkCommissionImportVo data) {

        return data.getBusinessCode();
    }

    @Override
    public void invokeBefore(LzshHandworkCommissionImportVo data) {
        access = false;
        for (LzshAgentInfoRelationVo lzshInfo : infoList) {
            if (data.getBusinessCode().equals(lzshInfo.getBusinessCode()) &&
                data.getAgentName().equals(lzshInfo.getAgentName()) &&
                data.getChannel().equals(lzshInfo.getChannel()) &&
                data.getNetworkName().equals(lzshInfo.getNetworkName()) &&
                data.getShopCode().equals(lzshInfo.getShopCode()))
            {
                access = true;
                break;
            }
        }
        if (access == false) {
            data.ACCESS = false;
        }
        //商家上个月的数据，插入这个月的数据
//        if (hwcList != null)
        for (int i = 0; i < hwcList.size(); i++) {
            if (data.getBusinessCode().equals(hwcList.get(i).getBusinessCode()) &&
                data.getAgentName().equals(hwcList.get(i).getAgentName()) &&
                data.getAccountPeriod().compareTo(hwcList.get(i).getAccountPeriod()) > 0
            ) {
                lzshHandworkCommissionService.deleteByBcAndAn(data.getBusinessCode(), data.getAgentName());
                hwcList.removeIf(handworkCommission -> handworkCommission.getBusinessCode().equals(data.getBusinessCode())
                    && handworkCommission.getAgentName().equals(data.getAgentName()));
            }
        }
        //写入租户id和创建者id，避免调用自动填充然后多线程环境下租户id分配不足出现注入警告
        data.setTenantId("000000");
        data.setCreateBy(LoginHelper.getUserId());

    }

    @Override
    public void invokeAfter(LzshHandworkCommissionImportVo data) {

    }

}
